// boost_asio.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
using namespace boost::asio;
using namespace boost;

class a_timer
{
public:
  template<typename F> a_timer(io_service& ios, int x, F func)
    : f(func), count_max(x), count(0), t(ios, posix_time::milliseconds(500))
  {
    t.async_wait(bind(&a_timer::call_func, this, placeholders::error));
  }

  void call_func(const system::error_code&)
  {
    if(count >= count_max)
      return;

    ++count;
    f();
    t.expires_at(t.expires_at()+posix_time::milliseconds(500));
    t.async_wait(bind(&a_timer::call_func, this, placeholders::error));
  }
protected:
private:
  int count;
  int count_max;
  function<void()> f;
  deadline_timer t;
};

void print1()
{
  cout << "hello asio" << endl;
}

void print2()
{
  cout << "hello boost" << endl;
}

void resolv_connect(ip::tcp::socket& sock, const char* name, int port)
{
  ip::tcp::resolver rlv(sock.get_io_service());
  ip::tcp::resolver::query qry(name, lexical_cast<string>(port));

  ip::tcp::resolver::iterator iter = rlv.resolve(qry);
  ip::tcp::resolver::iterator end;
  system::error_code ec = error::host_not_found;

  for(; ec&&iter != end; ++iter)
  {
    sock.close();
    sock.connect(*iter, ec);
  }

  if(ec)
  {
    cout << "cann't connect." << endl;
    throw system::system_error(ec);
  }

  cout << "connect success." << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
  try
  {
    io_service ios;
    ip::tcp::socket sock(ios);
    resolv_connect(sock, "10.100.4.51", 6801);

    ios.run();
  }
  catch (...)
  {

  }

	return 0;
}

